//
//  SearchResultController.m
//  YiBaoStore
//
//  Created by 毛云河 on 2018/10/25.
//  Copyright © 2018年 小河. All rights reserved.
//

#import "SearchResultController.h"


@interface SearchResultController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *tableViewArray;
//搜索框
@property (nonatomic, strong) UITextField *searchTF;
@property (nonatomic, copy) NSString *nextPageInfo;

@property (nonatomic, strong) YHAlertView *alertView;

@end

@implementation SearchResultController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self createTableView];
    self.tableViewArray = [NSMutableArray array];
    [self httpRequestData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSString *isReload = USER_DEFAULTS_GET(@"isReload");
    if (NOEmptyStr(isReload))
    {
        USER_DEFAULTS_SAVE(@"", @"isReload");
        self.tableViewArray = [NSMutableArray array];
        [self httpRequestData];
    }
}

- (void)httpRequestMoreData
{
    if (IsEmptyStr(self.nextPageInfo))
    {
        [self ShowHUDWithMessage:@"商品已全部加载，暂无更多"];
        [self.myTableView.mj_footer endRefreshingWithNoMoreData];
    }
    else {
        [self httpRequestData];
    }
    
}

- (void)httpRequestData
{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:self.key_word forKey:@"title"];
    [dic setValue:@"0" forKey:@"categoryId"];
    
    NSString *itemState = USER_DEFAULTS_GET(@"itemState");
    if (IsEmptyStr(itemState))
    {
       [dic setValue:@"true" forKey:@"isPlatform"];//平台
    }
    else {
        [dic setValue:@"false" forKey:@"isPlatform"];//自营
        [dic setValue:itemState forKey:@"itemState"];//自营状态 0下架 1上架 2审核
    }
    
    NSLog(@"key_word-%@",self.key_word);
    
    if (NOEmptyStr(self.nextPageInfo))
    {
        [dic setValue:self.nextPageInfo forKey:@"nextPageInfo"];
        NSLog(@"key_word-%@",self.nextPageInfo);
    }
    __weak SearchResultController *myself = self;
    [HttpRequest formPostPath:SearchGoods_API params:dic resultBlock:^(NSDictionary *Data, MsgModel *msgModel)
     {
         NSLog(@"搜索商品列表--%@",Data);
         if (msgModel.status == 200)
         {
             NSError *error;
             NSDictionary *result = Data[@"result"];
             myself.nextPageInfo = result[@"nextPageInfo"];
             NSArray *currentPageResult = (NSArray *)result[@"currentPageResult"];
//             NSLog(@"currentPageResult--%@",currentPageResult);
//             NSLog(@"nextPageInfo--%@",myself.nextPageInfo);
             
             if (currentPageResult.count == 0|| [currentPageResult[0] allKeys].count == 0)
             {
                 [myself.myTableView.mj_footer endRefreshingWithNoMoreData];
             }
             else {
                 for (NSDictionary *dic in currentPageResult)
                 {
                     MainModel *model = [[MainModel alloc] initWithDictionary:dic error:&error];
                     [myself.tableViewArray addObject:model];
                 }
             }
             [myself.myTableView.mj_footer endRefreshing];
             [myself.myTableView reloadData];
         }
         else
         {
             [myself.myTableView.mj_footer endRefreshingWithNoMoreData];
         }
         
     }];
}

#pragma mark - 创建表视图
- (void)createTableView
{
    if (@available(iOS 11.0, *)) {
        self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+TopStatusHeight_xs, SCREENWIDTH, SCREENHEIGHT-64-TopStatusHeight_xs-BottomHeight_xs) style:UITableViewStyleGrouped];
    } else {
        // Fallback on earlier versions
        self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64+TopStatusHeight, SCREENWIDTH, SCREENHEIGHT-64-TopStatusHeight-BottomHeight) style:UITableViewStyleGrouped];
    }
    [self.view addSubview:self.myTableView];
    self.myTableView.backgroundColor = RGBACOLOR(241, 241, 241, 1);
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.sectionHeaderHeight = 0.01f;
    self.myTableView.sectionFooterHeight = 10.f;
    self.myTableView.tableHeaderView = [self createHeaderView];
    self.myTableView.tableFooterView = [self tableViewFoot];
    //    self.myTableView.rowHeight = 100; 固定高度的cell
    [TTKUtil setAutomaticallyAdjustsScrollViewInsetsWidth:self.myTableView withView:self];
    
    NSString *itemState = USER_DEFAULTS_GET(@"itemState");
    if (IsEmptyStr(itemState))
    {
        [self.myTableView registerClass:[GoodsListCell class] forCellReuseIdentifier:@"GoodsListCell"];
    }
    else {
        [self.myTableView registerClass:[StorageShoppingCell class] forCellReuseIdentifier:@"StorageShoppingCell"];
    }
    
    
    self.myTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(httpRequestMoreData)];
    //self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getNewData)];
}

- (UIView *)createHeaderView
{
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.frame = CGRectMake(0, 0, SCREENWIDTH, 70);
    
    //搜索框
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [bgView addSubview:searchBtn];
    searchBtn.frame = CGRectMake(SCREENWIDTH-15-40, 10+5, 40, 40);
    [searchBtn addTarget:self action:@selector(searchBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *searchIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"sear_shopping"]];
    [bgView addSubview:searchIcon];
    searchIcon.frame = CGRectMake(SCREENWIDTH-15-18, 10+11, 18, 18);
    
    self.searchTF = [[UITextField alloc] init];
    [bgView addSubview:self.searchTF];
    self.searchTF.frame = CGRectMake(15, 10+5, SCREENWIDTH-30-40, 40);
    self.searchTF.font = FontWithSize(14);
    self.searchTF.placeholder = @"请输入商品名称";
    self.searchTF.text = self.key_word;
    
    //分割线
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(15, 10+45, SCREENWIDTH-30, 1)];
    [bgView addSubview:lineView];
    lineView.backgroundColor = BtnBgColor;
    return bgView;
}

- (UIView *)tableViewFoot
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 0.01)];
    return view;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    [self.myTableView tableViewDisplayWitMsg:@"没有找到符合条件商品" ifNecessaryForRowCount:self.tableViewArray.count];
    return self.tableViewArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *itemState = USER_DEFAULTS_GET(@"itemState");
    if (IsEmptyStr(itemState))
    {
        return 375.f;
    }
    else {
        return 145.f;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *itemState = USER_DEFAULTS_GET(@"itemState");
    if (IsEmptyStr(itemState))
    {
        GoodsListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"GoodsListCell"];
        cell.shanrkBtn.indexPath = indexPath;
        cell.changePriceBtn.indexPath = indexPath;
        cell.recommendBtn.indexPath = indexPath;
        [cell.shanrkBtn addTarget:self action:@selector(shanrkBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell.changePriceBtn addTarget:self action:@selector(changePriceBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell.recommendBtn addTarget:self action:@selector(recommendBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        cell.topTiteLabelBtn.indexPath = indexPath;
        cell.leftImageBtn.indexPath = indexPath;
        cell.rightImgaeBtn.indexPath = indexPath;
        [cell.topTiteLabelBtn addTarget:self action:@selector(gotoGoodsDeilt:) forControlEvents:UIControlEventTouchUpInside];
        [cell.leftImageBtn addTarget:self action:@selector(gotoGoodsDeilt:) forControlEvents:UIControlEventTouchUpInside];
        [cell.rightImgaeBtn addTarget:self action:@selector(gotoGoodsDeilt:) forControlEvents:UIControlEventTouchUpInside];
        
        MainModel *model = self.tableViewArray[indexPath.section];
        [cell setCellModel:model];
        
        return cell;
    }
    else {
        
        StorageShoppingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"StorageShoppingCell"];
        if ([itemState isEqualToString:@"0"])
        {//下架的自营商品 仓库商品
            cell.index = 3;
        }
        else if ([itemState isEqualToString:@"1"])
        {//上架的自营商品
            cell.index = 1;
        }
        else if ([itemState isEqualToString:@"2"])
        {//审核中的自营商品
            cell.index = 2;
        }
        
        MainModel *model = self.tableViewArray[indexPath.section];
        [cell setCellWithMode:model];
        
        cell.editBtn.indexPath = indexPath;
        cell.delectBtn.indexPath = indexPath;
        cell.putawayBtn.indexPath = indexPath;
        
        [cell.editBtn addTarget:self action:@selector(editBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell.delectBtn addTarget:self action:@selector(delectBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell.putawayBtn addTarget:self action:@selector(putawayBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }
}

#pragma mark - 编辑按钮
- (void)editBtnClick:(UIButton *)sender
{
    NSLog(@"编辑商品");
    MainModel *model = self.tableViewArray[sender.indexPath.section];
    EditGoodsController *editVC = [[EditGoodsController alloc] init];
    editVC.model = model;
    
    NSString *itemState = USER_DEFAULTS_GET(@"itemState");
    if ([itemState isEqualToString:@"0"])
    {//下架的自营商品 仓库商品
        editVC.index = 3;
    }
    else if ([itemState isEqualToString:@"1"])
    {//上架的自营商品
        editVC.index = 1;
        editVC.hidesBottomBarWhenPushed = YES;
    }
    else if ([itemState isEqualToString:@"2"])
    {//审核中的自营商品
        editVC.index = 2;
        editVC.hidesBottomBarWhenPushed = YES;
    }
    
    [self.navigationController pushViewController:editVC animated:YES];
}

#pragma mark - 删除按钮点击事件
- (void)delectBtnClick:(UIButton *)sender
{
    NSString *itemState = USER_DEFAULTS_GET(@"itemState");
    if ([itemState isEqualToString:@"0"])
    {//下架的自营商品 仓库商品
        NSLog(@"在当下是删除");
        MYHAleartView *alertView = [[MYHAleartView alloc] initMecommendAlertViewWithMessage:@"确认要删除该商品吗？" fuText:@"" sureBtnTitle:@"确认删除" cancleBtnTitle:@"保留商品"];
        [alertView showAlertView];
        
        MainModel *model = self.tableViewArray[sender.indexPath.section];
        NSInteger index = sender.indexPath.section;
        __weak SearchResultController *myself = self;
        
        alertView.sureBlock = ^(id  _Nonnull sender)
        {
            NSLog(@"确认删除");
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:model.product_id forKey:@"itemId"];
            [dic setValue:@"-1" forKey:@"state"];
            
            [HttpRequest formPostPath:UpdateShoppingState_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
             {
                 if (msgModel.status == 200)
                 {
                     [myself.tableViewArray removeObjectAtIndex:index];
                     [myself.myTableView reloadData];
                 }
             }];
        };
    }
    else if ([itemState isEqualToString:@"1"])
    {//上架的自营商品
        NSLog(@"在当下是下架");
        MYHAleartView *alertView = [[MYHAleartView alloc] initMecommendAlertViewWithMessage:@"确认要下架该商品吗？" fuText:@"" sureBtnTitle:@"确认下架" cancleBtnTitle:@"保留商品"];
        [alertView showAlertView];
        
        MainModel *model = self.tableViewArray[sender.indexPath.section];
        NSInteger index = sender.indexPath.section;
        __weak SearchResultController *myself = self;
        
        alertView.sureBlock = ^(id  _Nonnull sender)
        {
            NSLog(@"确认下架");
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:model.product_id forKey:@"itemId"];
            [dic setValue:@"0" forKey:@"state"];
            
            [HttpRequest formPostPath:UpdateShoppingState_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
             {
                 if (msgModel.status == 200)
                 {
                     [myself.tableViewArray removeObjectAtIndex:index];
                     [myself.myTableView reloadData];
                 }
             }];
        };
    }
    else if ([itemState isEqualToString:@"2"])
    {//审核中的自营商品
        NSLog(@"在这个界面是删除");
        MYHAleartView *alertView = [[MYHAleartView alloc] initMecommendAlertViewWithMessage:@"确认要删除该商品吗？" fuText:@"" sureBtnTitle:@"确认删除" cancleBtnTitle:@"保留商品"];
        [alertView showAlertView];
        
        MainModel *model = self.tableViewArray[sender.indexPath.section];
        NSInteger index = sender.indexPath.section;
        __weak SearchResultController *myself = self;
        
        alertView.sureBlock = ^(id  _Nonnull sender)
        {
            NSLog(@"确认删除");
            NSMutableDictionary *dic = [NSMutableDictionary dictionary];
            [dic setValue:model.product_id forKey:@"itemId"];
            [dic setValue:@"-1" forKey:@"state"];
            
            [HttpRequest formPostPath:UpdateShoppingState_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
             {
                 if (msgModel.status == 200)
                 {
                     [myself.tableViewArray removeObjectAtIndex:index];
                     [myself.myTableView reloadData];
                 }
             }];
        };
    }
}

- (void)putawayBtnClick:(UIButton *)sender
{
    NSString *itemState = USER_DEFAULTS_GET(@"itemState");
    if ([itemState isEqualToString:@"0"])
    {//下架的自营商品 仓库商品
        NSLog(@"上架商品");
        MainModel *model = self.tableViewArray[sender.indexPath.section];
        self.alertView = [[YHAlertView alloc] initPutawayAlertViewWithModel:model];
        [self.alertView showAlertView];
        
        __weak SearchResultController *myself = self;
        self.alertView.BtnBlock = ^(NSInteger index)
        {
            if (index == 1)
            {//去编辑界面
                EditGoodsController *editVC = [[EditGoodsController alloc] init];
                editVC.model = model;
                editVC.index = 3;
                editVC.hidesBottomBarWhenPushed = YES;
                [myself.navigationController pushViewController:editVC animated:YES];
            }
            else {//2 确认上架
                [myself surePutaway:sender.indexPath];
            }
        };
    }
    else if ([itemState isEqualToString:@"1"])
    {//上架的自营商品
        NSLog(@"这个界面是分享");
        MainModel *model = self.tableViewArray[sender.indexPath.section];
        //前往分享商品视图
        SharkShoppingVC *shopping = [[SharkShoppingVC alloc] init];
        shopping.hidesBottomBarWhenPushed = YES;
        shopping.product_id = model.product_id;
        shopping.isHide = YES;//自营隐藏
        [self.navigationController pushViewController:shopping animated:YES];
    }
    else if ([itemState isEqualToString:@"2"])
    {//审核中的自营商品
        NSLog(@"在这个界面是上架");
        MainModel *model = self.tableViewArray[sender.indexPath.section];
        self.alertView = [[YHAlertView alloc] initPutawayAlertViewWithModel:model];
        [self.alertView showAlertView];
        
        __weak SearchResultController *myself = self;
        self.alertView.BtnBlock = ^(NSInteger index)
        {
            if (index == 1)
            {//去编辑界面
                EditGoodsController *editVC = [[EditGoodsController alloc] init];
                editVC.model = model;
                editVC.index = 2;
                editVC.hidesBottomBarWhenPushed = YES;
                [myself.navigationController pushViewController:editVC animated:YES];
            }
            else {//2 确认上架
                [myself surePutaway:sender.indexPath];
            }
        };
    }
}

- (void)surePutaway:(NSIndexPath *)indexPath
{
    MainModel *model = self.tableViewArray[indexPath.section];
    
    __weak SearchResultController *myself = self;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:model.product_id forKey:@"itemId"];
    [dic setValue:@"2" forKey:@"state"];
    
    [HttpRequest formPostPath:UpdateShoppingState_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
     {
         if (msgModel.status == 200)
         {
             [myself.alertView removeAlerrView];
             [self ShowHUDWithMessage:@"上架成功"];
             USER_DEFAULTS_SAVE(@"2", @"isReload");
             myself.tableViewArray = [NSMutableArray array];
             [myself httpRequestData];
             [myself.myTableView reloadData];
         }else {
             [self ShowHUDWithMessage:@"上架失败"];
         }
     }];
}

- (void)gotoGoodsDeilt:(UIButton *)sender
{
    NSLog(@"%@",@"前往商品详情页");
}

#pragma mark - 搜索按钮
- (void)searchBtnClick:(UIButton *)sender
{
    [self.searchTF resignFirstResponder];
    self.key_word = self.searchTF.text;
    NSLog(@"key_word-%@",self.key_word);
    [self httpRequestData];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(nonnull UITableViewCell *)cell forRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    
}

#pragma mark - cell上面的分享btn
- (void)shanrkBtnClick:(UIButton *)sender
{
    MainModel *model = self.tableViewArray[sender.indexPath.section];
    //前往分享商品视图
    SharkShoppingVC *shopping = [[SharkShoppingVC alloc] init];
    shopping.product_id = model.product_id;
    shopping.isHide = NO;
    [self.navigationController pushViewController:shopping animated:YES];
}

#pragma mark - 推荐按钮绑定事件
- (void)recommendBtnClick:(UIButton *)sender
{
    MainModel *model = self.tableViewArray[sender.indexPath.section];
    MYHAleartView *alertView = [[MYHAleartView alloc] initMecommendAlertViewWithMessage:@"确认推荐该商品吗？" fuText:@"" sureBtnTitle:@"确认" cancleBtnTitle:@"取消"];
    [alertView showAlertView];
    
    __weak SearchResultController *myself = self;
    alertView.sureBlock = ^(id  _Nonnull sender)
    {
        NSLog(@"确认");
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:model.product_id forKey:@"itemId"];
        [HttpRequest formPostPath:AddRecommend_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
         {
             NSLog(@"推荐商品Data--%@",Data);
             dispatch_async(dispatch_get_main_queue(), ^{
                 [myself httpRequestData];
             });
         }];
    };
}

#pragma mark - 改价b绑定事件
- (void)changePriceBtnClick:(UIButton *)sender
{
    MainModel *model = self.tableViewArray[sender.indexPath.section];
    MYHAleartView *alertView = [[MYHAleartView alloc] initChangPriceWithModel:model];
    [alertView showAlertView];
    __weak SearchResultController *myself = self;
    alertView.moneyBlock = ^(CGFloat number)
    {
        NSLog(@"%0.2f",number);
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:model.product_id forKey:@"itemId"];
        [dic setValue:[NSString stringWithFormat:@"%0.2f",number] forKey:@"price"];

        [HttpRequest formPostPath:EditGoods_API params:dic resultBlock:^(id Data, MsgModel *msgModel)
         {
             NSLog(@"改价Data--%@",Data);
             [myself httpRequestData];
         }];
    };
}

@end
